package cn.xyinping.user.controller;

import cn.xyinping.basic.exception.MyException;
import cn.xyinping.basic.util.AjaxResult;
import cn.xyinping.basic.util.PageList;
import cn.xyinping.user.domain.User;
import cn.xyinping.user.dto.UserDto;
import cn.xyinping.user.query.UserQuery;
import cn.xyinping.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 27266
 * @desrciption
 * @date 2021/10/29
 */
@RestController
@RequestMapping("/user")
// @Api(tags = "用户接口",description = "用户接口详细描述")
public class UserController {
    @Autowired
    private IUserService iUserService;

    @GetMapping("{id}")
//  @ApiOperation(value = "查询一条数据",notes = "传一个id")
    public User loadById(@PathVariable("id") long id){
        return iUserService.findOne(id);
    }
    @GetMapping
//   @ApiOperation(value = "查询所有",notes = "不需要参数")
    public List<User> queryAll (){
        return iUserService.findAll();
    }
    @PostMapping
//    @ApiOperation(value = "分页查询",notes = "分页。。。")
    public PageList<User> queryPage(@RequestBody UserQuery query){
        return iUserService.queryList(query);
    }
    @DeleteMapping("{id}")
//    @ApiOperation(value = "根据id删除",notes = "传一个id")
    public AjaxResult delete(@PathVariable long id){
        try {
            iUserService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("系统繁忙");
        }
    }
    @PatchMapping
//    @ApiOperation(value = "批量删除",notes = "传id数组")
    public AjaxResult pathDelete(@RequestBody List<Long> ids){
        try {
            iUserService.patchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("系统异常");
        }
    }
    @PutMapping
//    @ApiOperation(value = "用户添加或修改",notes = "如果有id就是修改否则就是添加")
    public AjaxResult addByUpdata(@RequestBody User user){
        try {
            if(user.getId()==null){
                iUserService.add(user);
            }else {
               iUserService.update(user);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("系统繁忙");
        }
    }

    /**
     * 手机号注册
     * @return
     */
    @PostMapping("/phone/registr")
    public AjaxResult phoneRegister(@RequestBody UserDto userDto){
        try {
            iUserService.phoneRegister(userDto);
            return AjaxResult.me();
        } catch (MyException e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("系统繁忙");
        }
    }
}

